package com.halflife.comeElectricity.orderMng.history;

import com.halflife.framework.dto.Result;
import com.halflife.comeElectricity.member.rider.Rider;
import com.halflife.comeElectricity.orderMng.order.*;
import com.halflife.comeElectricity.orderMng.order.vo.OrderVO;
import com.halflife.shiro.utils.ShiroUtil;
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.shape.Rectangle;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2018/3/12 0012.
 */
@RestController
@RequestMapping("rider_historyOrder")
public class HistoryOrderRiderController {

    private Logger log = LoggerFactory.getLogger(HistoryOrderRiderController.class);

    @Resource
    private HistoryOrderRepository historyOrderRepository;
    @Resource
    private HistoryOrderExtRepository historyOrderExtRepository;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private OrderExtRepository orderExtRepository;

    /**
     * 生成歷史訂單 並刪除訂單 add by liuj
     * @param orderId
     * @param request
     */
    @PostMapping("/add/{orderId}")
    @ResponseStatus(HttpStatus.CREATED)
    public Result add(@PathVariable Integer orderId, HttpServletRequest request){

        try {
            BeanUtilsBean beanUtilsBean = new BeanUtilsBean();
            beanUtilsBean.getConvertUtils().register(new org.apache.commons.beanutils.converters.BigDecimalConverter(null), BigDecimal.class);
            //查詢訂單以及訂單詳情
            if(orderId!=null) {
                //获取订单
                Order order = orderRepository.selectByPrimaryKey(orderId);
                //更新訂單狀態 3已完成
                order.setStatus(OrderEnum.FINISHED.m_orderStatus.byteValue());
                //复制Order对象
                HistoryOrder order_h = new HistoryOrder();
                beanUtilsBean.copyProperties(order_h, order);
                order_h.setId(null);
                //创建取消订单
                Integer histroyOrderId = historyOrderRepository.insert(order_h);
                //获取订单详情
                OrderExt orderExt = orderExtRepository.selectByPrimaryKey(orderId);
                //复制订单详情
                HistoryOrderExt orderExt_h = new HistoryOrderExt();
                beanUtilsBean.copyProperties(orderExt_h, orderExt);
                //指定订单详情id对应CancelOrder
                orderExt_h.setId(order_h.getId());
                //创建取消订单详情
                historyOrderExtRepository.insert(orderExt_h);
                //删除订单以及订单详情
                orderRepository.deleteByPrimaryKey(orderId);
                orderExtRepository.deleteByPrimaryKey(orderId);
            }
            return Result.Ok();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.No("系统异常");
        }
    }
    //获取已完成订单管理列表 edit by liuj3
    @GetMapping("/list")
    @ResponseStatus(HttpStatus.CREATED)
    // public ResponseEntity<List<CancelOrder>> list(@RequestParam(value="id",defaultValue = "null") Integer id,
    public ResponseEntity<HistoryOrderCallBack> list(@RequestParam(value="longitude", required = false) Integer longitude,
                                                     @RequestParam(value="latitude", required = false) Integer latitude,
                                                     @RequestParam(value="currentPage",defaultValue = "1") Integer currentPage,
                                                     @RequestParam(value="pageSize",defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest request){
        //oper 分页类型 0-进行中订单 1-已完成订单 -1-已取消订单
        Rider rider  =  ShiroUtil.getRider(request);
        if (longitude != null && latitude != null) {
            int radius =1;//千米
            SpatialContext geo = SpatialContext.GEO;
            Rectangle rectangle = geo.getDistCalc().calcBoxByDistFromPt(
                    geo.makePoint(longitude, latitude), radius * DistanceUtils.KM_TO_DEG, geo, null);
            System.out.println(rectangle.getMinX() + "-" + rectangle.getMaxX());// 经度范围
            System.out.println(rectangle.getMinY() + "-" + rectangle.getMaxY());// 纬度范围
        }
        //推送分页Map参数
        HashMap<String, Object> param = new HashMap();
        param.put("currentPage", (currentPage-1)*pageSize);
        param.put("pageSize", pageSize);
        param.put("riderId", rider.getId());
        int totalCount = historyOrderRepository.selectHistoryCountOrderByPage(param);
        List<HistoryOrder> list = historyOrderRepository.selectHistoryOrderByPage(param);
        //创建返回对象
        HistoryOrderCallBack  b = new HistoryOrderCallBack();
        //推送订单列表
        b.setList(list);
        //计算总页数
        int totalPage = totalCount/pageSize;
        if(totalCount%pageSize!= 0)
            totalPage++;
        b.setTotalPage(totalPage);
        return new ResponseEntity<HistoryOrderCallBack>(b, HttpStatus.OK);
    }

    @GetMapping("/vo/{id}")
    public ResponseEntity<OrderVO> getVObyId(@PathVariable Integer id, HttpServletRequest request) {
        OrderVO orderExt = historyOrderExtRepository.selectVOById(id);
        return new ResponseEntity<OrderVO>(orderExt, HttpStatus.OK);

    }
}
